<?php

namespace app\admin\controller\onlineclassroom;

use app\common\controller\Backend;
use app\common\model\OnlineClassroomUser as OnlineClassroomUserModel;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 空中课堂用户申请管理
 *
 * @icon fa fa-users
 * @controllerRoute onlineclassroom/onlineclassroomuser
 */
class Onlineclassroomuser extends Backend
{
    /**
     * OnlineClassroomUser模型对象
     * @var \app\common\model\OnlineClassroomUser
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OnlineClassroomUserModel;
        
        // 状态列表
        $statusList = [
            '0' => '待审核',
            '1' => '已通过', 
            '2' => '已拒绝',
            '3' => '已取消'
        ];
        $this->view->assign("statusList", $statusList);
    }

    /**
     * 查看申请列表
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'approveAdmin'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $total=$list->total();
            foreach ($list as $row) {
                // 只显示需要的用户字段
                if ($row->getRelation('user')) {
                    $row->getRelation('user')->visible(['id', 'username', 'nickname', 'mobile', 'email']);
                }
                if ($row->getRelation('approveAdmin')) {
                    $row->getRelation('approveAdmin')->visible(['id', 'username', 'nickname']);
                }
            }
            $list = collection($list->items())->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['city_id']=model("Cityarea")->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                $list[$i]['school_id']=model("School")->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核申请
     */
    public function approve($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->status != 0) {
            $this->error('该申请已经处理过了');
        }

        if ($this->request->isPost()) {
            $params = $this->request->post();
            $status = $params['status'] ?? '';
            $reject_reason = $params['reject_reason'] ?? '';

            if (!in_array($status, [1, 2, '1', '2'])) {
                $this->error('审核状态不正确');
            }

            if ($status == 2 || $status == '2') {
                if (empty($reject_reason)) {
                    $this->error('拒绝申请时必须填写拒绝理由');
                }
            }

            // 确保状态为整数
            $numericStatus = (int)$status;

            $result = OnlineClassroomUserModel::approve($ids, $numericStatus, $this->auth->id, $reject_reason);
            
            if ($result) {
                $this->success('审核成功', '', '/onlineclassroom/onlineclassroomuser?ref=addtabs');
            } else {
                $this->error('审核失败');
            }
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量审核
     */
    public function batchApprove()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        $ids = $this->request->post("ids");
        $status = $this->request->post("status");
        $reject_reason = $this->request->post("reject_reason", "");

        if (empty($ids) || !in_array($status, [1, 2, '1', '2'])) {
            $this->error('参数错误');
        }

        if ($status == 2 || $status == '2') {
            if (empty($reject_reason)) {
                $this->error('批量拒绝时必须填写拒绝理由');
            }
        }

        // 确保状态为整数
        $numericStatus = (int)$status;

        $idsArray = explode(',', $ids);
        $successCount = 0;

        Db::startTrans();
        try {
            foreach ($idsArray as $id) {
                if (OnlineClassroomUserModel::approve($id, $numericStatus, $this->auth->id, $reject_reason)) {
                    $successCount++;
                }
            }
            Db::commit();
            $this->success("成功处理 {$successCount} 条申请", '', '/onlineclassroom/onlineclassroomuser?ref=addtabs');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('批量审核失败：' . $e->getMessage());
        }
    }

    /**
     * 查看申请详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->with(['user', 'approveAdmin'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除申请记录
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->delete();
            if ($list) {
                $this->success(__('Deleted successfully'));
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 添加申请记录
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                $params['create_time'] = date('Y-m-d H:i:s');
                $result = $this->model->allowField(true)->save($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($this->model->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑申请记录
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    if (empty($row['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    if (empty($row['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                }
                
                $params['update_time'] = date('Y-m-d H:i:s');
                $result = $row->allowField(true)->save($params);
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error($row->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}